import axios from 'axios'

const state = function () {
  return {
    cart: []
  }
}

const getters = {
  /**
   * 件数
   * @param state
   * @returns {number}
   */
  total (state) {
    console.log(Array.from(state.cart).length)
    return state.cart.reduce((pre, next) => pre + next.count, 0)
  },
  /**
   * 结算总价
   */
  sum (state) {
    return state.cart.reduce((pre, next) => pre + next.count * next.price, 0)
  }
}

const mutations = {
  async getCartData (state) {
    const res = await axios.get('http://localhost:3000/cart')
    console.log(res)
    state.cart = Array.from(res.data)
  },
  /**
   * 修改商品数量
   * @param state
   */
  updateCount (state, {
    id,
    num
  }) {
    const goods = state.cart.filter(item => item.id === id)[0]
    goods.count += num
    axios.patch(`http://localhost:3000/cart/${id}`, { count: goods.count })
  }
}

const actions = {}

export default {
  state,
  getters,
  mutations,
  actions,
  namespaced: true
}
